function userMessageS(){
    return new Promise((reslove,reject)=>{
        axios({
            url:'/picture/session',
        }).then((data)=>{
            reslove(data)
        }).catch((err)=>{
            reject(err)
        })
    })
}
let sessionUserid = null
userMessageS().then(data=>{
    if(data.data.session){
        sessionUserid=data.data.session.id
    }
})
//userId又被我写死了！！！！
let userIdDie = 1
 
// 封装选择器函数
function $(selector){
    var c=selector.substring(0,1);//获取第一个字符
    if(c=="#"){
        return document.getElementById(selector.substring(1,selector.length));//返回相应的元素
    }else if(c == '.'){
        return document.getElementsByClassName(selector.substring(1,selector.length))
    }else{
        return document.getElementsByTagName(selector);
    }
}

function userMessageS(){
    return new Promise((reslove,reject)=>{
        axios({
            url:'/picture/session',
        }).then((data)=>{
            reslove(data)
        }).catch((err)=>{
            reject(err)
        })
    })
}
userMessageS().then(data=>{
    sessionUserid=undefined
    if(data.data.session){
        sessionUserid=data.data.session.id
    }



//选择专辑的样式
var albumList = $('.albumList')


//创建专辑之后要出来输入框
var creatAlbum = $('.creatAlbum')[0]
    creatInput = $('.creatInput')[0]
    width = 0
    timer = null
    cuttimer = null
    openInput = true
    albumUl = $('.albumUl')[0]
creatAlbum.onclick = function(){
    if(openInput == false){
        if(creatInput.value != '') {
            let str = null
            if($('.albumUl')[0].children[0].innerHTML == '您还没有专辑，点击创建吧！'){
                str = ''
            }else{
                str = albumUl.innerHTML
            }
            //判断字数有没有大于7
            if(creatInput.value.length > 7){
                tigs('专辑名字字数不得大于7！！！',false)
            }else{
                axios({
                    url:'/index/createAlbum',
                    data:{
                        userId:sessionUserid,
                        albumName:creatInput.value
                    },
                    method:'post'
                }).then(data=>{
                    console.log(data)
                    if(data.data.data.code == 200001){
                        tigs(`${data.data.data.message}`,false)
                    }else{
                        albumUl.innerHTML = str+`
                        <li class="albumList" onclick = selectAlbum(this) data-albumId=${data.data.data.data} >${creatInput.value}</li>
                        `
                    }
                    
                    console.log(data)
                }).catch(err=>{
                    console.log(err)
                })
                
            }
            
        }
        downWidth()
    }else{
        addWidth()
    }
}
function addWidth(){
    width += 5
    creatInput.style.width = `${width}px`
    if(width >= 200){
        openInput = false
        clearTimeout(timer)
    }else{
        timer = setTimeout(addWidth,1)
    }
}
function downWidth(){
    width -= 5
    creatInput.style.width = `${width}px`
    if(width < 0){
        openInput = true
        creatInput.value = ''
        clearTimeout(cuttimer)
    }else{
        cuttimer = setTimeout(downWidth,1)
    }
}



})


//获得帖子照片的数组
function getPicLength(path){
    if(path == null){
        return ' '
    }else{
        let imgSrc = path.split('::')
        return imgSrc

    }
}

//照片数组，改变布局
function picLayout(picArr){
    let str = `<h5>已选择图片</h5>`
    for(let i = 0;i < picArr.length;i++){
        // console.log(dataURLtoFile(picArr[i],`file${i}`))
        imgFormData.append(`file${i}`,dataURLtoFile(picArr[i],`file${i}`),'temp.jpg')//把草稿里面的东西放到formData里面
        str += `
        <div class="imgBox">
            <img src="${picArr[i]}" onload='imgOnload(this)'/>
            <div class="opacity">
                <p class="deleteImg" onclick='delImg(this)' data-index=${i}>x</p>
            </div>
        </div>
        `
    }
    return str
}


//处理图片
//将base64转换为文件
function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}


let albumId = null
for(let i = 0;i < $('.albumUl')[0].children.length;i++){
    if($('.albumUl')[0].children[i].innerHTML == '默认专辑'){
        albumId = $('.albumUl')[0].children[i].getAttribute('data-albumId')
    }
}
function selectAlbum(a){
    for(let i = 0;i < $('.albumUl')[0].children.length;i++){
        if($('.albumUl')[0].children[i] == a){
            a.style.backgroundColor = '#ffa1a9'
            a.style.color = 'white'
            albumId = a.getAttribute('data-albumId')
        }else{
            $('.albumUl')[0].children[i].style.backgroundColor = 'white'
            $('.albumUl')[0].children[i].style.color = '#777777'
        }
    }
}
let classify = null
function selectClassfy(a){
    
    for(let i = 0;i < $('.tipUl')[0].children.length;i++){
        if($('.tipUl')[0].children[i] == a){
            // if(a.style.backgroundColor == 'rgb(255, 161, 169)'){
            //     a.style.backgroundColor = 'white'
            //     a.style.color = '#777777'
            // }else{
            //     a.style.backgroundColor = '#ffa1a9'
            //     a.style.color = 'white'
            // }
            a.style.backgroundColor = '#ffa1a9'
            a.style.color = 'white'
            classify = a.getAttribute('data-classfyId')
        }else{
            $('.tipUl')[0].children[i].style.backgroundColor = 'white'
            $('.tipUl')[0].children[i].style.color = '#777777'
        }
    }
}





//文件转为base64
// function fileToBase64(a) {
//     let imgStr = `<h5>已选择图片</h5>`
//     for(let i = 0;i < a.files.length;i++){
//         var txt = a.files[i];
//             formData = new FormData()
//         formData.append('img[]', txt);
//         var src = window.URL.createObjectURL(txt);
//         imgStr += `
//         <div class="imgBox">
//             <img src="${src}" onload='imgOnload(this)'/>
//             <div class="opacity">
//                 <p class="deleteImg" onclick='delImg(this)' data-index=${i}>x</p>
//             </div>
//         </div>
//         ` 
//     }
    
//     $('.readyPic')[0].innerHTML = imgStr
// }




let deleteImg = $('.deleteImg')
let imgBox = $('.imgBox')
let readyPic = $('.readyPic')[0]
var imgFormData = new FormData()
let imgArr = []
var imageUpload = $('.imageUpload')[0]
// imageUpload.onchange = function(){
//     //重新选择之后要先清空formData里面二点东西
//     // readyPic.innerHTML = '<h5>已选择图片</h5>'
//     imgFormData = new FormData()
//     fileToBase64(imageUpload)
//     for(let i = 0;i < imageUpload.files.length;i++){
//         imgFormData.append(`file${i}`,imageUpload.files[i])
//     }
//     imageUpload.value = ''

// }

function delImg(a){
    let index = a.getAttribute('data-index')
    let indexx = Number(index) + 1
    imgFormData.delete(`file${index}`)//删掉imgFormData里这个文件
    console.log(indexx)
    readyPic.children[indexx].innerHTML = ''
    imgStr = $('.readyPic')[0].innerHTML
}



//确认存为草稿按钮
let textarea = $('textarea')[0]
$('.draft')[0].onclick = ()=>{
    //判断有没有选过图片
    if(ifPic){
        //如果没有图片就不能保存成草稿了
        if(!!imgFormData.entries().next().value){//表单为空就是false
            let ifLength = 0
            for(let i = 1;i < $('.readyPic')[0].children.length;i++){
                if($('.readyPic')[0].children[i].innerHTML != ''){
                    ifLength += 1
                }else{
                    continue
                }
            }
            if(ifLength <= 9){
                if(ifDraft){
                    $('.getDraftAgain')[1].style.display = 'block'
                }else{
                    $('.draftName')[0].style.display = 'block'
                }
            }else{
                tigs('最多选择九张图片！！！',false)
            }
        }else{
            tigs('请选择图片！',false)
        }
    }else{
        tigs('请至少选择一张图片',false)
    }
    
    
}

//关闭草稿起名字
let closeDraftName = ()=>{
    $('.draftName')[0].style.display = 'none'
    $('.draftNameInput')[0].value = ""
}
$('.closeDraftName')[0].onclick = closeDraftName



//确认草稿名字，就是确认保存草稿
$('.saveDraft')[0].onclick = ()=>{
    //判断草稿名字填了没有
    if($('.draftNameInput')[0].value){
        $('.black')[0].style.display = 'block'
        NProgress.start()
        NProgress.set(0.7)
        NProgress.inc()
        axios({
            method:'post',
            url:`/index/draft?userId=${Number(sessionUserid)}&context=${textarea.value}&draftName=${$('.draftNameInput')[0].value}`,   
            data:imgFormData,
            headers: {
                'Content-Type': "multipart/form-data",
            },
        })
        .then(data=>{
            console.log(data)
            //保存成功
            if(data.data.data.data){
                imgFormData = new FormData()
                $('.readyPic')[0].innerHTML = '<h5>已选择图片</h5>'
                textarea.value = ''
                closeDraftName()
                NProgress.done()
                tigs('草稿保存成功',true)
            }else{
                NProgress.done()    
                tigs(`${data.data.data.message}，请重新设置草稿名`,false)
            }
            $('.black')[0].style.display = 'none'
            console.log(data.data.data)
            // tigs('成功存为草稿',true)
        })
        .catch(err=>{
            console.log(err)
        })
    }else{
        tigs('请输入草稿名字',false)
    }
    
}


//输入框字数限制
textarea.oninput = ()=>{
    $('.fontMax')[0].innerHTML = `还可以输入${500-textarea.value.length}字`
}


//确认发布按钮
$('.pubishBtn')[0].onclick = function(){
    //如果没有选标签
    if(classify == null){
        tigs('请选择标签！！',false)
    }else{
        //上传文件数量大于9
        let ifLength = 0
        for(let i = 1;i < $('.readyPic')[0].children.length;i++){
            if($('.readyPic')[0].children[i].innerHTML != ''){
                ifLength += 1
            }else{
                continue
            }
        }
        if(ifLength <= 9){
            //有图片
            if(!!imgFormData.entries().next().value){
                if(ifDraft){//改的是草稿
                    $('.getDraftAgain')[0].style.display = 'block'
                }else{
                    $('.black')[0].style.display = 'block'
                    NProgress.start()
                    NProgress.set(0.7)
                    NProgress.inc()
                    let context = textarea.value
                    axios({
                        method:"post",
                        url:`/index/publish?albumId=${albumId}&classify=${classify}&context=${context}&userId=${sessionUserid}`,
                        data:imgFormData,
                        headers: {
                            'Content-Type': "multipart/form-data",
                        },
                    }).then(data=>{
                        $('.black')[0].style.display = 'none'
                        NProgress.done()
                        textarea.value = ''
                        tigs('发布成功，即将前往您的个人主页！',true)
                        setTimeout(function(){
                            window.location.href = `/picture/picture`
                        },3000)
                    }).catch(err=>{
                        console.log(err)
                    })
                }
            }else{
                tigs('请至少选择一张图片！！！',false)
            }
        }else{
            tigs('上传图片数量不得大于9张！',false)
        }
        
    }

}

$('.getNo')[0].onclick = ()=>{
    $('.getDraftAgain')[0].style.display = 'none'
}
$('.getOk')[0].onclick = ()=>{
    $('.black')[0].style.display = 'block'
    NProgress.start()
    NProgress.set(0.7)
    NProgress.inc()
    let context = textarea.value
    axios({
        method:"post",
        url:`/index/publish?albumId=${albumId}&classify=${classify}&context=${context}&userId=${sessionUserid}&draftName=${$('.getDraftAgain')[0].getAttribute('data-thisDraft')}`,
        data:imgFormData,
        headers: {
            'Content-Type': "multipart/form-data",
        },
    }).then(data=>{
        $('.getDraftAgain')[0].style.display = 'none'
        $('.black')[0].style.display = 'none'
        NProgress.done()
        textarea.value = ''
        tigs('发布成功，即将前往您的个人主页！',true)
        setTimeout(function(){
            window.location.href = `/picture/picture`
        },3000)
    }).catch(err=>{
        console.log(err)
    })
}
$('.getNo')[1].onclick = ()=>{
    $('.getDraftAgain')[1].style.display = 'none'
}
//从草稿保存草稿
$('.getOk')[1].onclick = ()=>{
    
    //保存草稿
    axios({
        method:'post',
        url:`/index/draft?userId=${Number(sessionUserid)}&context=${textarea.value}&draftName=${$('.getDraftAgain')[1].getAttribute('data-thisDraft')}`,   
        data:imgFormData,
        headers: {
            'Content-Type': "multipart/form-data",
        },
    })
    .then(data=>{
        //保存成功
        if(data.data.data.data){
            imgFormData = new FormData()
            $('.readyPic')[0].innerHTML = '<h5>已选择图片</h5>'
            textarea.value = ''
            $('.getDraftAgain')[1].style.display = 'none'
            NProgress.done()
            tigs('草稿保存成功',true)
        }
        $('.black')[0].style.display = 'none'
        console.log(data.data.data)
        // tigs('成功存为草稿',true)
    })
    .catch(err=>{
        console.log(err)
    })
}










//让图片居中显示
function imgOnload(e) {
	var wid = e.parentNode.offsetWidth;//父容器限制高度
	var hei = e.parentNode.offsetHeight;//父容器限制宽度
	var realWidth = e.width; //储存图片实际宽度
	var realHeight = e.height; //储存图片实际高度
	//获取图片宽高比
	var realwh = e.width / e.height;
	if(realwh > wid/hei) {
		var w = ((hei / realHeight) * realWidth) + 'px';
		var h = hei + 'px';
		var l = '-' + ((hei / realHeight) * realWidth - wid) / 2 + 'px';
		e.style.width = w; //等比缩放宽度
		e.style.height = h; //跟div高度一致
		e.style.left = l; //设置图片相对自己位置偏移为img标签的宽度-高度的一半
		e.style.position = 'relative';
	} else {
		var w = wid +'px';
		var h = ((wid / realWidth) * realHeight) + 'px';
		var t = '-' + ((wid / realWidth) * realHeight - hei) / 2 + 'px';
		e.style.width = w; //等比缩放宽度
		e.style.height = h; //跟div高度一致
		e.style.top = t; //设置图片相对自己位置偏移为img标签的宽度-高度的一半
		e.style.position = 'relative';
	}
}



//点击上传图片要出来画布
$('.uploadBox')[0].onclick = function () {
    $('.centerLeft')[0].innerHTML = ''
    // $('.centerRight')[0].innerHTML = `
    // <p>图片预览:</p>
    // <div class="small"/>
    // <div class="small"/>
    // `
    $('.box')[0].style.display = 'block'

}

let cropper = null

//获取用户选择的图片比例
let getScale = ()=>{
    for(let i = 0;i < $('.select')[0].children.length;i++){
        if($('.select')[0].children[i].selected == true){
            return $('.select')[0].children[i].innerHTML
        }
    }
}

let ifPic = false//判断用户有没有选择过图片
//换图片比例
$('.select')[0].onchange = ()=>{
    let scale = getScale()
    let height = scale.split('/')[1]
    let width = scale.split('/')[0]
    if(ifPic){
        //用户选过图片
        // $('.centerLeft')[0].innerHTML = ''
        cropper.setAspectRatio(width/height)
    }else{
        //用户没有选
    }
    
}


$('.cropperInput')[0].onchange = function () {
    ifPic = true
    let scale = getScale()
    let height = scale.split('/')[1]
    let width = scale.split('/')[0]
    let styleHeight = 200/width*height
    $('.small')[0].style.height = `${styleHeight}px`
    fileToBase64(this)//把图片放到画布上
    // // 使用cdn引入Js
    cropper = new Cropper(image, {
        aspectRatio: width / height,//裁剪框的比例
        viewMode: 1,//图片跟背景布的位置关系
        guides: false,//取消裁剪框上的虚线
        preview: '.small',//生成预览图的效果地方
        // background:true,
        crop: function (e) {//裁剪过程执行的函数

        }
    });
}




//将file转为base64
function fileToBase64(a) {
    var txt = a.files[0];
    formData = new FormData()
    formData.append('img[]', txt);
    var src = window.URL.createObjectURL(txt);
    //判断宽高
    $('.centerLeft')[0].innerHTML = `
    <img src='${src}' id='image'/>
    `
    let headImg = $('.centerLeft')[0].children[0]
    //图片加载完之后
    headImg.onload = function () {
        let imgWidth = headImg.offsetWidth
        let imgHeight = headImg.offsetHeight
        if (imgWidth > imgHeight) {
            headImg.style.width = '100%'
            headImg.style.height = 'auto'
        } else {
            headImg.style.width = 'auto'
            headImg.style.height = '100%'
        }
    }

}

//复位按钮
$('.resetBtn')[0].onclick = function () {
    if (ifInput()) {
        cropper.reset()
    }
}
//旋转按钮
$('.rotateBtn')[0].onclick = function () {
    if (ifInput()) {
        cropper.rotate(90)
    }
}
//换向按钮
var scale = true
$('.huanXiangBtn')[0].onclick = function () {
    if (ifInput()) {
        if (scale) {
            cropper.scale(-1, 1)
            scale = false
        } else {
            cropper.scale(1, 1)
            scale = true
        }
    }
}
//判断有没有选择图片
function ifInput() {
    if ($('.cropperInput')[0].files[0]) return true
    else return false
}



//确定裁剪
$('.crop')[0].onclick = function () {
    if (ifInput()) {
        // NProgress.start()
        // NProgress.set(0.7)
        // NProgress.inc()
        var file = null 
        let headImg = 'headImg'
        //获取用户当前选择的图片的下标
        let picIndex = $('.readyPic')[0].children.length-1
        cropper.getCroppedCanvas().toBlob(b => {
            imgFormData.append(`file${picIndex}`,b,'temp.jpg');
            // NProgress.done()
            let str = `
            <div class="imgBox">
                <img src="${cropper.getCroppedCanvas().toDataURL()}"/>
                <div class="opacity">
                    <p class="deleteImg" onclick='delImg(this)' data-index=${picIndex}>x</p>
                </div>
            </div>
            `
            $('.readyPic')[0].innerHTML += str
            closeCrop()
        })

    }
}


function closeCrop(){
    $('.box')[0].style.display = 'none'
    if(ifPic){
        cropper.destroy()
    }else{
        //用户选择过图片
    }
}
$('.scloseCropper')[0].onclick = closeCrop

let ifDraft = false//判断当前写的是草稿还是一个新的文章

//点击我的草稿要选择一个
$('.getMyDraftBtn')[0].onclick = ()=>{
    NProgress.start()
    NProgress.set(0.7)
    NProgress.inc()
    axios({
        method:"get",
        url:"/index/getDraftsList",
        params:{
            userId:sessionUserid
        },
    }).then(data=>{
        NProgress.done()
        console.log(data)
        if(data.data.data.code == 200001){
            tigs(`${data.data.data.message}`,false)
        }else{
            
            $('.allMyDraft')[0].style.display = 'block'
            let list = data.data.data.data
            let str = ''
            for(let i = 0;i < list.length;i++){
                str += `
                <option>${list[i].draftName}</option>
                `
            }
            $('.selectDraft')[0].innerHTML = str
        }
    }).catch(err=>{
        console.log(err)
    })
}
//确定获取草稿
$('.getDraftBtn')[0].onclick = ()=>{
    $('.black')[0].style.display = 'block'
    NProgress.start()
    NProgress.set(0.7)
    NProgress.inc()
    let draftName = null
    //获取用户选择的草稿名字
    for(let i = 0;i < $('.selectDraft')[0].children.length;i++){
        if($('.selectDraft')[0].children[i].selected == true){
            draftName = $('.selectDraft')[0].children[i].innerHTML
        }
    }
    axios({
        method:"get",
        url:"/index/getDrafts",
        params:{
            draftName:draftName,
            userId:sessionUserid
        }
    }).then(data=>{
        ifPic = true
        ifDraft = true
        console.log(data)
        $('.getDraftAgain')[0].setAttribute('data-thisDraft',draftName)
        $('.getDraftAgain')[1].setAttribute('data-thisDraft',draftName)
        if(data.data.data.data.path != undefined){

        }else{
            console.log('这个文章没有图片这是不对的！！！')
        }
        let str = picLayout(data.data.data.data.path)
        $('.readyPic')[0].innerHTML = str
        $('textarea')[0].value = data.data.data.data.Context
        $('.fontMax')[0].innerHTML = `还可以输入${500-textarea.value.length}字`
        tigs('填充草稿完成', true)
        $('.black')[0].style.display = 'none'
        closeMyDraft()
        NProgress.done()
    }).catch(err=>{
        console.log(err)
    })
}




let closeMyDraft = ()=>{
    $('.allMyDraft')[0].style.display = 'none'
}

$('.closeMyDraft')[0].onclick = closeMyDraft